package com.example.easyhttp.jwt;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * Created by Administrator on 2018/4/13.
 */

public class DBWebSignature {
    public static String secret = "Moego&Key&*@#%";// 测试密匙

    public static String delimiter = ".";

    public static String getEncryption(String payload) throws InvalidKeyException, NoSuchAlgorithmException {
        JSONObject header = getHeader();
        String headerbase64 = getheader(header);
        String payloadbase64 = getpoyload(payload);
        String input = headerbase64 + delimiter + payloadbase64;


        String signstr = getsign(input);
        String new_signstr = signstr.replace("+", "-").replace("/", "_").replace("=", "");
        String token = headerbase64 + delimiter + payloadbase64 + delimiter + new_signstr;
        return token;
    }

    private static JSONObject getHeader() {
        JSONObject header = new JSONObject();
        try {
            header.put("typ", "JWT");
            header.put("alg", "HS256");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return header;
    }

    public static String getheader(JSONObject header) {
        String headerSegment = base64str(header.toString());
        return headerSegment;
    }

    public static String getpoyload(String payload) {
        String payloadSegment = base64str(payload);
        return payloadSegment;

    }

    public static String getsign(String message) throws NoSuchAlgorithmException, InvalidKeyException {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
//        String sign=sha256_HMAC.doFinal(message.getBytes()).toString();
//        String signstr=base64str(sign);
        String hashs = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));

        return hashs;
    }


    public static String base64str(String str) {
        String result = Base64.getEncoder().encodeToString(str.getBytes());
        result = result.replace("+", "-").replace("/", "_").replace("=", "");
        return result;
    }

}
